package com.sand.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.entity.HouseEntity;
import com.sand.entity.OrdertableEntity;
import com.sand.service.IHouseService;
import com.sand.service.IOrderService;
import com.sand.util.DateTool;
import com.sand.util.ModelTest;
import com.sand.util.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

@Controller
@RequestMapping(value = "order")
public class OrderController {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/12/5/005 22:38
 */
    //orderService接口
    @Resource(name = "orderService")
    private IOrderService orderService;
    //获取房子信息接口
    @Autowired
    private IHouseService houseService;

    //分页查询提问
    @RequestMapping(value = "/queryOrderLimit")
    public void queryOrderLimit(int limit, int page, String condition, int showWi, HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");

        PageModel<HashMap<String, Object>> pm = orderService.queryOrderLimit(limit, page,showWi, condition);
        ModelTest<List<HashMap<String, Object>>> listData = new ModelTest<List<HashMap<String, Object>>>("OK",pm.getList(),0, pm.getPagecount());
        response.getWriter().write(JSON.toJSON(listData).toString());
    }
    //根据id查询订单
    @RequestMapping(value = "/queryOrderById")
    public ModelAndView queryOrderById(int rid ,int showWi){
        ModelAndView mv = new ModelAndView().addObject("orderShow", orderService.queryOrderById(rid));

        switch (showWi){
            case 1://后台数据展示
                mv.setViewName("layui/page/table_order_show");
                break;
            case 2://前台数据展示
                mv.setViewName("");
                break;
        }
        return mv;
    }

    /**
     * 前端房东订单信息分页查询
     * @param limit
     * @param page
     * @param condition
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/queryOrderByUserIdLimit")
    public void queryOrderByUserIdLimit(int limit,int page,String condition,HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");
        PageModel<HashMap<String, Object>> model = orderService.queryOrderByUserIdLimit(limit, page, condition);
        response.getWriter().write(JSON.toJSON(model).toString());
        System.out.println(JSON.toJSON(model).toString());
    }

    /**
     * 查询租客订单信息
     * @param limit
     * @param page
     * @param condition
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/queryTenantOrderViewLimit")
    public void queryTenantOrderViewLimit(int limit,int page,String condition,HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");
        PageModel<HashMap<String, Object>> model = orderService.queryTenantOrderViewLimit(limit, page, condition);
        response.getWriter().write(JSON.toJSON(model).toString());
        System.out.println(JSON.toJSON(model).toString());
    }

    //删除订单
    @RequestMapping(value = "/delOrder")
    public void delOrder(@RequestParam("oid")int oid,
                         HttpServletRequest request,
                         HttpServletResponse response)throws Exception{
        boolean bln = orderService.delOrder(oid);
        if(bln){
            response.getWriter().write("OK");
        }else{
            response.getWriter().write("NO");
        }
    }

    //查询房东钱包信息
    @RequestMapping(value = "/Wallet")
    public void queryHouseByUserIdLimit(int oderUserId,HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setCharacterEncoding("utf-8");
        Map<String,Object> map = orderService.queryWallet(oderUserId);
        response.getWriter().write(JSON.toJSON(map).toString());
        System.out.println(JSON.toJSON(map).toString());
    }

    //==========================lyl=========================

    //添加订单
    @RequestMapping("/addNewOrder")
    @ResponseBody
    public String addNewOrder(@RequestParam("hid")int hid,
                              @RequestParam("enddate")String endDate,
                              HttpServletRequest request,
                              HttpServletResponse response) throws ParseException {
        //设置传参对象
        JSONObject json = new JSONObject();
        //获取登录对象
        HashMap<String,Object> loginMap;
        if(request.getSession().getAttribute("drom")!=null){
            loginMap = (HashMap<String, Object>) request.getSession().getAttribute("drom");
            //获取房屋信息
            HouseEntity house = houseService.queryHouseData(hid);
            if(house!=null){
                //计算房子总租金
                int paymothed = house.getPaymentMethod();//付款方式
                long price = house.getPrice();//月租
                int time = DateTool.getMothDiffer(endDate)-1;
                int endPrece = -1;
                if(paymothed==0){
                    endPrece = ((int)price*time);
                }else{
                    endPrece = (int) (((int)price*time)+price);
                }
                //获取当前时间
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date datess = dateFormat.parse(endDate);
                //设置持久化对象
                OrdertableEntity ordertable = new OrdertableEntity();
                ordertable.setStatus(0);
                ordertable.setHouseId(hid);
                ordertable.setUserId((int)loginMap.get("rid"));
                ordertable.setLeaseEffectiveTime(new Timestamp(new Date().getTime()));
                ordertable.setLeaseExpirationTime(new Timestamp(datess.getTime()));
                ordertable.setTotalRentalPrice(endPrece);
                if(orderService.addOrder(JSON.toJSONString(ordertable))){
                    json.put("statecode",0);
                    json.put("msg","您的订单已确认");
                }else{
                    json.put("statecode",1);
                    json.put("msg","无法确认请稍后重试");
                }
            }else{
                json.put("statecode",1);
                json.put("msg","无法查询到该房子信息");
            }
        }else{
            json.put("statecode",1);
            json.put("msg","您未登录");
        }

        return json.toJSONString();
    }

    //获取订单内内房子的id
    @RequestMapping("/gethouseids")
    public void getHouseId(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        //获取登录对象信息
        HashMap loginMap = null;
        if(request.getSession().getAttribute("drom")!=null){
            loginMap = (HashMap) request.getSession().getAttribute("drom");
        }else{
            response.getWriter().write("");
        }

        //设置传参对象
        JSONObject json = new JSONObject();
        List list = orderService.queryHouseIdList((int)loginMap.get("rid"));
        if(list!=null&&list.size()>0){
            json.put("data",list);
            response.getWriter().write(json.toJSONString());
        }else{
            json.put("data",null);
            response.getWriter().write(json.toJSONString());
        }
    }



    //查询订单表
    @RequestMapping("/queryList")
    public void queryList(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        //设置传参对象
        JSONObject json = new JSONObject();
        //获取登录者信息
        HashMap<String,Object> loginMap = null;
        if(request.getSession().getAttribute("drom")!=null){
            loginMap= (HashMap<String, Object>) request.getSession().getAttribute("drom");

            List<HashMap<String ,Object>> endlist = orderService.queryOlderList((int)loginMap.get("rid"));
            if(endlist!=null&&endlist.size()>0){
                json.put("data",endlist);
                response.getWriter().write(json.toJSONString());
            }
        }else{
        }
    }










    //确认订单
    @RequestMapping(value = "/updateOrderStatus")
    public String updateOrderStatus(int rid){
        boolean bln = orderService.updateOrderStatus(rid);
        if(bln){
            return "renting/pages/tenant/contract";
        }
        return "renting/pages/tenant/inspection";
    }
}
